function varargout = bciMappingTool(varargin)
% BCIMAPPINGTOOL M-file for bciMappingTool.fig
%      BCIMAPPINGTOOL, by itself, creates a new BCIMAPPINGTOOL or raises the existing
%      singleton*.
%
%      H = BCIMAPPINGTOOL returns the handle to a new BCIMAPPINGTOOL or the handle to
%      the existing singleton*.
%
%      BCIMAPPINGTOOL('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in BCIMAPPINGTOOL.M with the given input arguments.
%
%      BCIMAPPINGTOOL('Property','Value',...) creates a new BCIMAPPINGTOOL or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before bciMappingTool_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to bciMappingTool_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help bciMappingTool

% Last Modified by GUIDE v2.5 15-Nov-2012 11:16:12

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @bciMappingTool_OpeningFcn, ...
                   'gui_OutputFcn',  @bciMappingTool_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before bciMappingTool is made visible.
function bciMappingTool_OpeningFcn(hObject, eventdata, handles, varargin)
global BCIMAP;
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to bciMappingTool (see VARARGIN)

% Choose default command line output for bciMappingTool
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes bciMappingTool wait for user response (see UIRESUME)
% uiwait(handles.figure1);
BCIMAP.bci=bciGetParam();
[BCIMAP.hdr BCIMAP.bci] = bciReadRecorderHeader(BCIMAP.bci);
BCIMAP.bci=bciInit(BCIMAP.bci);
set(handles.text6,'string',...
    sprintf('Detected Channels: %i @ %4.1f Hz', BCIMAP.hdr.nChans,BCIMAP.hdr.Fs));
set(handles.edit4,'string',num2str(BCIMAP.bci.chanOfInterest));
set(handles.edit3,'string',num2str(1/BCIMAP.bci.param.winsrate));
set(handles.edit2,'string',num2str(BCIMAP.bci.param.winsize));
set(handles.uipanel1,'SelectedObject',handles.radiobutton1);
BCIMAP.compareMethod='rsqu';
BCIMAP.blockCount = 0;
BCIMAP.nDatCond = [];
BCIMAP.conditions = [];

% --- Outputs from this function are returned to the command line.
function varargout = bciMappingTool_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;



function edit1_Callback(hObject, eventdata, handles)
% hObject    handle to edit1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit1 as text
%        str2double(get(hObject,'String')) returns contents of edit1 as a double


% --- Executes during object creation, after setting all properties.
function edit1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function edit2_Callback(hObject, eventdata, handles)
% hObject    handle to edit2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit2 as text
%        str2double(get(hObject,'String')) returns contents of edit2 as a double


% --- Executes during object creation, after setting all properties.
function edit2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function edit3_Callback(hObject, eventdata, handles)
% hObject    handle to edit3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit3 as text
%        str2double(get(hObject,'String')) returns contents of edit3 as a double


% --- Executes during object creation, after setting all properties.
function edit3_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function edit4_Callback(hObject, eventdata, handles)
% hObject    handle to edit4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit4 as text
%        str2double(get(hObject,'String')) returns contents of edit4 as a double


% --- Executes during object creation, after setting all properties.
function edit4_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit4 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
global BCIMAP;
% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
BCIMAP.bci=bciGetParam();
[BCIMAP.hdr BCIMAP.bci] = bciReadRecorderHeader(BCIMAP.bci);

set(handles.text6,'string',...
    sprintf('Detected Channels: %i @ %4.1f Hz', BCIMAP.hdr.nChans,BCIMAP.hdr.Fs));
set(handles.edit1,'enable','on');
set(handles.edit2,'enable','on');
set(handles.edit3,'enable','on');
set(handles.edit4,'enable','on');
BCIMAP.blockCount = 0;
BCIMAP.nDatCond = [];
BCIMAP.conditions = [];
set(handles.text5,'string',sprintf('Collected Data: %i',sum(BCIMAP.nDatCond)));

% --- Executes on button press in pushbutton3.
function pushbutton3_Callback(hObject, eventdata, handles)
global BCIMAP;
% hObject    handle to pushbutton3 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
curCond = str2double(get(handles.edit5,'string'));
if isnan(curCond),
    errordlg('Invalid condition No.','Error');
    return;
end
if ~any(BCIMAP.conditions==curCond), % add new condition
    BCIMAP.conditions=cat(2,BCIMAP.conditions,curCond);
    BCIMAP.nDatCond(length(BCIMAP.nDatCond)+1)=0;
end

if sum(BCIMAP.nDatCond)==0,
    BCIMAP.bci.param.winsize = str2double(get(handles.edit2,'string'));
    BCIMAP.bci.param.winsrate = 1/str2double(get(handles.edit3,'string'));
    BCIMAP.bci.chanOfInterest = str2num(get(handles.edit4,'string'));
    BCIMAP.bci=bciInit(BCIMAP.bci);

    set(handles.edit1,'enable','off');
    set(handles.edit2,'enable','off');
    set(handles.edit3,'enable','off');
    set(handles.edit4,'enable','off');
end

BCIMAP.blockCount = BCIMAP.blockCount + 1;

if get(handles.chkKeepRawdata,'value')==1,
    [BCIMAP.Dat{BCIMAP.blockCount}.trainEpoch,...
        BCIMAP.Dat{BCIMAP.blockCount}.badChanMap,...
        BCIMAP.Dat{BCIMAP.blockCount}.rawdata] = ...
            mappingGetBuffer(BCIMAP.bci,str2double(get(handles.edit1,'string')));
else
    [BCIMAP.Dat{BCIMAP.blockCount}.trainEpoch,...
        BCIMAP.Dat{BCIMAP.blockCount}.badChanMap] = ...
            mappingGetBuffer(BCIMAP.bci,str2double(get(handles.edit1,'string')));    
end
BCIMAP.Dat{BCIMAP.blockCount}.trainLabel = ...
    ones(size(BCIMAP.Dat{BCIMAP.blockCount}.trainEpoch,3),1)*curCond;
BCIMAP.nDatCond(BCIMAP.conditions==curCond) = ...
        BCIMAP.nDatCond(BCIMAP.conditions==curCond) + ...
        size(BCIMAP.Dat{BCIMAP.blockCount}.trainEpoch,3);
outputStr = sprintf('Collected Data (cond:nSamples): ');
for k=1:length(BCIMAP.nDatCond),
        if k<length(BCIMAP.nDatCond),
            strSep='/';
        else
            strSep='';
        end
        outputStr = [outputStr,sprintf('%i:%i%s',BCIMAP.conditions(k),BCIMAP.nDatCond(k)),strSep];
end
set(handles.text5,'string',outputStr);


% --- Executes on button press in pushbutton5.
function pushbutton5_Callback(hObject, eventdata, handles)
global BCIMAP;
% hObject    handle to pushbutton5 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

BCIMAP.bci.eventsToClassify = BCIMAP.conditions;
cond1 = str2double(get(handles.edit6,'string'));
cond2 = str2double(get(handles.edit7,'string'));
if isnan(cond1)||isnan(cond2),
    errordlg('Invalid expression in condition numbers to compare to.','Error');
    return
end
if ~any(cond1==BCIMAP.conditions)||~any(cond2==BCIMAP.conditions),
    errordlg('Invalid condition numbers to compare to.','Error');
    return
end    
if ~isfield(BCIMAP,'Dat')||length(BCIMAP.conditions)<2||any(BCIMAP.nDatCond==0),
    errordlg('Not enough data available for selected conditions.','Error');
    return
end
if isempty(BCIMAP.bci.chanOfInterest),
    errordlg('Invalid channel definition','Error');
    return
end
    
[BCIMAP.bci,Train]=bciGetTrainDat(BCIMAP.bci,BCIMAP.Dat);
BCIMAP.bci.eventsToClassify = [cond1 cond2];
W = bciMultiCompareFeatures(BCIMAP.bci,Train,BCIMAP.compareMethod,2);
figure;
bciTopoplotResults(BCIMAP.bci,W{1});


% --- Executes when user attempts to close figure1.
function figure1_CloseRequestFcn(hObject, eventdata, handles)
% hObject    handle to figure1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: delete(hObject) closes the figure
clear global BCIMAP
delete(hObject);



function edit5_Callback(hObject, eventdata, handles)
% hObject    handle to edit5 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit5 as text
%        str2double(get(hObject,'String')) returns contents of edit5 as a double


% --- Executes during object creation, after setting all properties.
function edit5_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit5 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in pushbutton8.
function pushbutton8_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton8 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global BCIMAP

[fileName,filePath] = uiputfile('*.mat','Save file name');
if ischar(fileName),
    save([filePath fileName],'BCIMAP');
end



function edit6_Callback(hObject, eventdata, handles)
% hObject    handle to edit6 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit6 as text
%        str2double(get(hObject,'String')) returns contents of edit6 as a double


% --- Executes during object creation, after setting all properties.
function edit6_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit6 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function edit7_Callback(hObject, eventdata, handles)
% hObject    handle to edit7 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of edit7 as text
%        str2double(get(hObject,'String')) returns contents of edit7 as a double


% --- Executes during object creation, after setting all properties.
function edit7_CreateFcn(hObject, eventdata, handles)
% hObject    handle to edit7 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --------------------------------------------------------------------
function uipanel1_SelectionChangeFcn(hObject, eventdata, handles)
% hObject    handle to uipanel1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
%retrieve GUI data, i.e. the handles structure
global BCIMAP;
 
switch get(handles.uipanel1,'selectedObject')   % Get Tag of selected object    
    case handles.radiobutton1
      BCIMAP.compareMethod='rsqu';
     case handles.radiobutton2
       BCIMAP.compareMethod='tval';
     case handles.radiobutton3
      BCIMAP.compareMethod='svm';
    otherwise
       % Code for when there is no match.
 
end
%updates the handles structure
guidata(hObject, handles);


% --- Executes on button press in pushbutton9.
function pushbutton9_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton9 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global BCIMAP

[fileName,filePath] = uigetfile('*.mat','Load file name');
if ischar(fileName),
    localBCIMAP=load([filePath fileName],'BCIMAP');
    BCIMAP=localBCIMAP.BCIMAP;
end

set(handles.edit2,'string',num2str(BCIMAP.bci.param.winsize));
set(handles.edit3,'string',num2str(1/BCIMAP.bci.param.winsrate));
set(handles.edit4,'string',num2str(BCIMAP.bci.chanOfInterest));
BCIMAP.bci=bciInit(BCIMAP.bci);

set(handles.edit1,'enable','off');
set(handles.edit2,'enable','off');
set(handles.edit3,'enable','off');
set(handles.edit4,'enable','off');

outputStr = sprintf('Collected Data (cond:nSamples): ');
for k=1:length(BCIMAP.nDatCond),
        if k<length(BCIMAP.nDatCond),
            strSep='/';
        else
            strSep='';
        end
        outputStr = [outputStr,sprintf('%i:%i%s',BCIMAP.conditions(k),BCIMAP.nDatCond(k)),strSep];
end
set(handles.text5,'string',outputStr);


% --- Executes on button press in chkKeepRawdata.
function chkKeepRawdata_Callback(hObject, eventdata, handles)
% hObject    handle to chkKeepRawdata (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of chkKeepRawdata


